import { Prisma } from '@prisma/client';
import prisma from '@/server/lib/prisma';
import { DeptSchema } from '@/server/lib/zodSchema';

export default defineEventHandler(async (event) => {
  try {
    const body = await readBody(event);
    DeptSchema.parse(body); // 校验参数

    // 校验部门名称是否已存在
    const isDeptName = await prisma.sys_dept.findFirst({
      where: {
        deptName: body.deptName
      }
    })
    if (isDeptName) {
      return {
        code: 400,
        msg: '部门名称已存在',
      }
    }

    const data: Prisma.sys_deptCreateInput   = {
      parentId: Number(body.parentId),
      deptName: body.deptName,
      ancestors: body.ancestors,
      orderNum: Number(body.orderNum),
      status: body.status,
      leader: body.leader,
      phone: body.phone,
      email: body.email,
    }
    const result = await prisma.sys_dept.create({
      data,
    })
    return {
      code: 200,
      data: result,
      msg: '创建成功'
    }
  } catch (error: any) {
    const err = JSON.parse(error);
    return {
      code: 400,
      msg: err[0].message || '未知错误',
    }
  } finally {
    await prisma.$disconnect(); // 关闭连接
  }
})